<?php
namespace Admin\Model;
use \Think\Model;

class TypeModel extends Model
{
	protected $_validate = array(
		array('tname','require','必须填入参数'),
	);

	protected $_auto = array(
		array('path','getPath',1,'callback'),	
	);

	//获取路径的方法
	protected function getPath(){
		//获取父类path和id
		$list = $this->field('tid,path')->find(I('fid'));
		if($list){
			return $list['path'].$list['tid'].',';
		}else{
			return "0,";
		}
	}

	public function getAdminCate($tid=0,$field=true){
		//获取所有分类信息
		$list = $this->field($field)->select();

		//处理分类信息
		$list = $this->getHtmlCate($list,'——',$tid,0);

		return $list;
	}







	public function getHomeCate($tid=0,$field=true){
		//获取所有分类信息
		$list = $this->field($field)->select();
		
		//处理分类信息
		$list = $this->getTreeCate($list,$tid,'child');
		// echo "<pre>";
		// print_r($list);
		// echo "</pre>";
		//如果 存在id
		

		if (is_numeric($tid) && $tid >0){
			$arr = $this->field($field)->find($tid);
			$arr['child'] = $list;
			return $arr;
		}
		return $list;
	}

	private function getHtmlCate($cate,$html="——",$fid=0,$level=0){
		//定义空数组
		$arr = array();
		//遍历数组
		foreach ($cate as $v) {
			if($v['fid'] == $fid){
				$v['html'] = str_repeat($html,$level);
				$v['level'] = $level;
				$arr[] = $v;
				$arr = array_merge($arr,$this->getHtmlCate($cate,$html,$v['tid'],$level+1));
			}
		}
		return $arr;
	}

	private function getTreeCate($cate,$fid=0,$tname="child"){
		$arr = array();
		//遍历
		foreach ($cate as $v) {
			if($v['fid'] == $fid){
				$v[$tname] = $this->getTreeCate($cate,$v['tid']);
				$arr[] = $v;
			}
			return $arr;
		}
	}













}